<?php
/**
*
* @package phpBB3
* @version $Id: ppkbb3cker_chat.php 1.000 2010-01-14 19:39:00 PPK $
* @copyright (c) 2010 PPK
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
if (!defined('IN_PHPBB') && !defined('IN_PORTAL'))
{
	exit;
}

$chat_id=$config['ppkbb_portal_chat'];
$chat=request_var('chat', '');
$chat_error=request_var('r', 0);
$dt=time();

// Check if the user has actually sent a forum ID with his/her request
// If not give them a nice error page.
if (!$chat_id)
{
	trigger_error(defined('IN_PORTAL') ? 'CHAT_PORTAL_ERROR' : 'CHAT_INDEX_ERROR');
}

$sql_from = FORUMS_TABLE . ' f';

$sql = "SELECT f.*
	FROM $sql_from
	WHERE f.forum_id = $chat_id";
$result = $db->sql_query($sql);
$chat_data = $db->sql_fetchrow($result);
$db->sql_freeresult($result);

if (!$chat_data)
{
	trigger_error(defined('IN_PORTAL') ? 'CHAT_PORTAL_ERROR' : 'CHAT_INDEX_ERROR');
}

($chat_data['forum_type'] == FORUM_POST && $chat_data['forumas']==2) ? $forum_aschat=1 : $forum_aschat=0;

if(!$forum_aschat)
{
	trigger_error(defined('IN_PORTAL') ? 'CHAT_PORTAL_ERROR' : 'CHAT_INDEX_ERROR');
}

$chat_alt = ($chat_data['forum_status'] == ITEM_LOCKED) ? $user->lang['FORUM_LOCKED'] : 0;

$user_window=$online_window=$form_window=$bar_window=false;
$online_message=$message_window=$chat_key=$s_forum_rules=$bbcode_window=$chat_action='';
$users=$del_users=$chat_link=$max_id=array();
$chat_user=0;
$user_ip=sprintf('%u', ip2long(@$_SERVER['REMOTE_ADDR']));
$is_guest=!$user->data['is_registered'] && $config['ppkbb_chat_guests'] && $user->data['user_id']==1 ? 1 : 0;
$user_id=$is_guest ? $user_ip-($user_ip*2) : $user->data['user_id'];
$is_guest ? $chat_key=md5($user_ip) : '';
$username=$user->data['username'];
$ppkbb_chat_height=my_split_config($config['ppkbb_chat_height'], 3, 'my_int_val');

if(!$chat_alt)
{
	$user->add_lang('mods/ppkbb3cker_chat');

	$query=('SELECT * FROM ' .PPKCHAT_USERS_TABLE. " WHERE room='{$chat_id}'");
	$result=$db->sql_query($query);
	while($row=$db->sql_fetchrow($result))
	{
		if($row['room']==$chat_id)
		{
			if($dt - $row['lastaccess'] < $config['ppkbb_chat_inactive_time'] && $row['chatkey'])
			{
				if($is_guest)
				{
					if($row['chatkey']==$chat_key)
					{
						if($chat && $chat!='exit' && $config['ppkbb_chat_autokill_onrefresh'] && $dt - $row['lastaccess'] < $config['ppkbb_chat_murefresh'])
						{
							trigger_error($user->lang['CHAT_REFRESH']);
						}
						$chat_user=$row['user_id'];
						$chat=='exit' ? '' : $chat='continue';
						$chat_action='exit';
					}
				}
				else
				{
					if($row['user_id']==$user_id && $row['chatkey']==$user->data['user_chatkey'])
					{
						if($chat && $chat!='exit' && $config['ppkbb_chat_autokill_onrefresh'] && $dt - $row['lastaccess'] < $config['ppkbb_chat_murefresh'])
						{
							trigger_error($user->lang['CHAT_REFRESH']);
						}
						$chat_user=$row['user_id'];
						$chat=='exit' ? '' : $chat='continue';
						$chat_action='exit';
						$chat_key=$row['chatkey'];
					}
				}
				$users[$row['user_id']]=$row;
			}
			else
			{
				$del_users[$row['user_id']]=$row['user_id'];
			}
		}
	}
	$db->sql_freeresult($result);

	if($del_users)
	{
		$query=('DELETE FROM ' .PPKCHAT_USERS_TABLE. " WHERE user_id IN(".implode(', ', $del_users).")");
		$result=$db->sql_query($query);
	}

	if($chat=='enter' && $chat_user)
	{
		$chat_action=$chat='exit';
		$chat_user=0;
	}

	$chat_link['exit']=append_sid("{$phpbb_root_path}".(defined('IN_PORTAL') ? 'portal' : 'index').".$phpEx", "f=$chat_id&amp;chat=exit#chat");
	$chat_link['enter']=append_sid("{$phpbb_root_path}".(defined('IN_PORTAL') ? 'portal' : 'index').".$phpEx", "f=$chat_id&amp;chat=enter#chat");
	$ppkbb_chat_marchive=my_split_config($config['ppkbb_chat_marchive'], 2, 'my_int_val');

	if(@$users[$user_id]['lastaccess'] && $dt < $users[$user_id]['lastaccess'])
	{
		$chat='exit';
		$user->lang['CHAT_LOGIN']=sprintf($user->lang['CHAT_BANNED'], date('Y-m-d H:i:s', $users[$user_id]['lastaccess']));
		$chat_link['enter']='<a href="javascript:void(0);">'.$user->lang['CHAT_ENTER'].'</a>';
	}
	if(($chat=='exit' && $chat_user) || ($chat_user && !$chat))
	{
		$query='DELETE FROM ' .PPKCHAT_USERS_TABLE. " WHERE user_id='{$user_id}' AND lastaccess < $dt AND room='$chat_id'";
		$result=$db->sql_query($query);

		/*$sql = 'UPDATE ' . USERS_TABLE . "
			SET user_chatkey = ''
			WHERE user_id = '" . $user_id ."' LIMIT 1";
		$result=$db->sql_query($sql);*/

		$chat_action='enter';
		unset($users[$user_id]);
		$chat_user=0;
	}

	//0-$is_adm 1-$is_mod 2-$is_canaddchatm 3-$is_canviewchatu
	//4-$is_canviewchatm 5-$is_candelchatm 6-$is_canskipchatktime
	//7-$is_canhiddeninchat 8-$is_canviewhiddinchat 9-$is_cansendchatpm
	//10-$is_canskipdisbutton 11-$is_canusesmilies 12-$is_canusebbcodes
	//13-$is_candelchatm2 14-$is_canusegmode 15-$is_canuseacommands
	//16-$is_canviewarchive
	$is_adm=$auth->acl_get('a_') && !$is_guest ? 1 : 0;
	$is_mod=($auth->acl_get('m_') || $auth->acl_getf_global('m_')) && !$is_guest ? 1 : 0;
	$is_canaddchatm=$auth->acl_get('f_canaddchatm', $chat_id) && $auth->acl_get('u_canaddchatm') ? 1 : 0;
	$is_canviewchatu=$auth->acl_get('f_canviewchatu', $chat_id) && $auth->acl_get('u_canviewchatu') ? 1 : 0;
	$is_canviewchatm=$auth->acl_get('f_canviewchatm', $chat_id) && $auth->acl_get('u_canviewchatm') ? 1 : 0;
	$is_candelchatm=$auth->acl_get('f_candelchatm', $chat_id) && $auth->acl_get('u_candelchatm') ? 1 : 0;
	$is_canskipchatktime=$auth->acl_get('f_canskipchatktime', $chat_id) && $auth->acl_get('u_canskipchatktime') ? 1 : 0;
	$is_canhiddeninchat=$auth->acl_get('f_canhiddeninchat', $chat_id) && $auth->acl_get('u_canhiddeninchat') ? 1 : 0;
	$is_canviewhiddinchat=$auth->acl_get('f_canviewhiddinchat', $chat_id) && $auth->acl_get('u_canviewhiddinchat') ? 1 : 0;
	$is_cansendchatpm=$config['ppkbb_chat_enable_pm'] && $auth->acl_get('f_cansendchatpm', $chat_id) && $auth->acl_get('u_cansendchatpm') ? 1 : 0;
	$is_canskipdisbutton=$auth->acl_get('f_canskipdisbutton', $chat_id) && $auth->acl_get('u_canskipdisbutton') ? 1 : 0;
	$is_canusesmilies=$auth->acl_get('f_canusesmilies', $chat_id) && $auth->acl_get('u_canusesmilies') ? 1 : 0;
	$is_canusebbcodes=$config['ppkbb_chat_enable_bbcodes'] && $auth->acl_get('f_canusebbcodes', $chat_id) && $auth->acl_get('u_canusebbcodes') ? 1 : 0;
	$is_candelchatm2=$auth->acl_get('f_candelchatm2', $chat_id) && $auth->acl_get('u_candelchatm2') && !$is_guest ? 1 : 0;
	$is_canusegmode=$config['ppkbb_chat_enable_gmode'] && $auth->acl_get('f_canusegmode', $chat_id) && $auth->acl_get('u_canusegmode') && !$is_guest ? 1 : 0;
	$is_canuseacommands=$config['ppkbb_chat_enable_acommands'] && $auth->acl_get('f_canuseacommands', $chat_id) && $auth->acl_get('u_canuseacommands') && !$is_guest ? 1 : 0;
	$is_canviewarchive=$ppkbb_chat_marchive[0] && $auth->acl_get('f_canviewarchive', $chat_id) && $auth->acl_get('u_canviewarchive') ? 1 : 0;

	$rights="$is_adm $is_mod $is_canaddchatm $is_canviewchatu $is_canviewchatm $is_candelchatm $is_canskipchatktime $is_canhiddeninchat $is_canviewhiddinchat $is_cansendchatpm $is_canskipdisbutton $is_canusesmilies $is_canusebbcodes $is_candelchatm2 $is_canusegmode $is_canuseacommands $is_canviewarchive";

	intval($config['ppkbb_chat_murefresh']) > 9 ? '' : $config['ppkbb_chat_murefresh']=10;

	!$is_canviewchatm ? $is_canaddchatm=0 : '';
	if($chat=='enter' && !$chat_user && ($is_canviewchatu || $is_canviewchatm))
	{
		/*if(!$chat_key)
		{

		}*/
		$ppkbb_chat_guests_option=my_split_config($config['ppkbb_chat_guests_option'], 3, array('strval', 'intval', 'strval'));
		if($is_guest)
		{
			$ppkbb_chat_guests_option[0] ? $user_lang=$ppkbb_chat_guests_option[0] : $user_lang=$user->data['user_lang'];
			isset($user->lang[$ppkbb_chat_guests_option[2]]) ? $username=$user->lang[$ppkbb_chat_guests_option[2]] : $username=$ppkbb_chat_guests_option[2] ? $ppkbb_chat_guests_option[2] : $user->data['username'];
			$username.=rand(1, $ppkbb_chat_guests_option[1]);
			$user_lang='ru';
			$user_dateformat = $config['default_dateformat'];
			$user_timezone = $config['board_timezone'];
			$user_dst = $config['board_dst'];
		}
		else
		{
			$chat_key=create_chatkey($user_id);
			if(!$chat_key)
			{
				trigger_error('CHAT_CHATKEY_ERROR');
			}
			$user_lang=$user->data['user_lang'];
			$user_dateformat = $user->data['user_dateformat'];
			$user_timezone = $user->data['user_timezone'];
			$user_dst = $user->data['user_dst'];
		}
		$username = str_replace('---', '- - -', $username);
		$query=('INSERT INTO ' .PPKCHAT_USERS_TABLE. " (username, rights, lastpost, room, lastaccess, user_id, chatkey, user_color, user_hidden, user_ip, user_lang, user_timezone, user_dst, user_dateformat) VALUES ('{$username}', '{$rights}', '".($dt-$config['ppkbb_chat_waittime'])."', '$chat_id', '".($dt-$config['ppkbb_chat_murefresh'])."', '{$user_id}', '{$chat_key}', '{$user->data['user_colour']}', '".($is_canhiddeninchat ? 1 : 0)."', '".$db->sql_escape($user_ip)."', '{$user_lang}', '{$user_timezone}', '{$user_dst}', '".$db->sql_escape($user_dateformat)."')");
		$result=$db->sql_query($query);
		$chat_action='exit';
		$chat_user=1;
	}

	@!$chat_action ? $chat_action='enter' : '';
	!$chat ? $chat='exit' : '';
	$link=$chat_link[$chat_action];

	if($is_canviewchatm && $chat_user)
	{
		$message_window=true;
		$query='SELECT MAX(id) id, MAX(date) date FROM ' .PPKCHAT_MESSAGES_TABLE. " WHERE room='{$chat_id}'";
		$result=$db->sql_query($query);
		$max_id=$db->sql_fetchrow($result);
	}
	else
	{
		if(!$is_canviewchatm)
		{
			$message_window=$user->lang['CHAT_CANT_VIEWCHATM'];
		}
	}

	if($is_canviewchatu && $chat_user)
	{
		$user_window=true;
	}
	else
	{
		if(!$chat_user)
		{
			$online_window=true;
			$users_online=array();
			if(sizeof($users))
			{
				foreach($users as $k => $v)
				{
					$user_rights=explode(' ', $v['rights']);
					if($v['user_hidden'] && $user_rights[7] && !$is_canviewhiddinchat || $v['lastaccess'] > $dt)
					{

					}
					else
					{
						$users_online[$k]=$v['user_id'] > 1 ? '<a href="'.append_sid("{$phpbb_root_path}memberlist.$phpEx", "mode=viewprofile&amp;u=".$v['user_id']).'"'.($v['user_color'] ? ' style="color:#'.$v['user_color'].';"' : '').'><b>'.$v['username'].'</b></a>' : '<b>'.$v['username'].'</b>';
					}
				}
			}
			$online_message='<b>'.$user->lang['CHAT_IN'].': </b>'. (sizeof($users_online) ? implode(', ', $users_online).' ('.sizeof($users_online).')' : '(0)');
		}
	}

	if($is_canaddchatm && $is_canviewchatm && $chat_user)
	{
		$form_window=true;
		if($is_canusesmilies)
		{
			$bar_window=true;
		}
		if($is_canusebbcodes)
		{
			$bbcode_window=true;
		}
	}
}

$template->assign_vars(array(
	'MODERATORS'	=> (!empty($moderators[$chat_id])) ? implode(', ', $moderators[$chat_id]) : '',

	'NEWEST_POST_IMG'			=> $user->img('icon_topic_newest', 'VIEW_NEWEST_POST'),
	'LAST_POST_IMG'				=> $user->img('icon_topic_latest', 'VIEW_LATEST_POST'),
	'FOLDER_IMG'				=> $user->img('topic_read', 'NO_NEW_POSTS'),
	'FOLDER_NEW_IMG'			=> $user->img('topic_unread', 'NEW_POSTS'),
	'FOLDER_HOT_IMG'			=> $user->img('topic_read_hot', 'NO_NEW_POSTS_HOT'),
	'FOLDER_HOT_NEW_IMG'		=> $user->img('topic_unread_hot', 'NEW_POSTS_HOT'),
	'FOLDER_LOCKED_IMG'			=> $user->img('topic_read_locked', 'NO_NEW_POSTS_LOCKED'),
	'FOLDER_LOCKED_NEW_IMG'		=> $user->img('topic_unread_locked', 'NEW_POSTS_LOCKED'),
	'FOLDER_STICKY_IMG'			=> $user->img('sticky_read', 'POST_STICKY'),
	'FOLDER_STICKY_NEW_IMG'		=> $user->img('sticky_unread', 'POST_STICKY'),
	'FOLDER_ANNOUNCE_IMG'		=> $user->img('announce_read', 'POST_ANNOUNCEMENT'),
	'FOLDER_ANNOUNCE_NEW_IMG'	=> $user->img('announce_unread', 'POST_ANNOUNCEMENT'),
	'FOLDER_MOVED_IMG'			=> $user->img('topic_moved', 'TOPIC_MOVED'),
	'REPORTED_IMG'				=> $user->img('icon_topic_reported', 'TOPIC_REPORTED'),
	'UNAPPROVED_IMG'			=> $user->img('icon_topic_unapproved', 'TOPIC_UNAPPROVED'),
	'GOTO_PAGE_IMG'				=> $user->img('icon_post_target', 'GOTO_PAGE'),

	'L_NO_TOPICS' 			=> ($chat_data['forum_status'] == ITEM_LOCKED) ? $user->lang['POST_FORUM_LOCKED'] : 0,

	'S_DISPLAY_POST_INFO'	=> ($chat_data['forum_type'] == FORUM_POST && ($auth->acl_get('f_post', $chat_id) || $user->data['user_id'] == ANONYMOUS)) ? true : false,

	'S_USER_CAN_POST'		=> ($auth->acl_get('f_post', $chat_id)) ? true : false,

	'S_FORUM_ACTION'		=> append_sid("{$phpbb_root_path}".(defined('IN_PORTAL') ? 'portal' : 'index').".$phpEx", "f=$chat_id"),
	'S_DISPLAY_SEARCHBOX'	=> ($auth->acl_get('u_search') && $auth->acl_get('f_search', $chat_id) && $config['load_search']) ? true : false,
	'S_SEARCHBOX_ACTION'	=> append_sid("{$phpbb_root_path}search.$phpEx", 'fid[]=' . $chat_id),
	'S_SINGLE_MODERATOR'	=> (!empty($moderators[$chat_id]) && sizeof($moderators[$chat_id]) > 1) ? false : true,
	'S_IS_LOCKED'			=> ($chat_data['forum_status'] == ITEM_LOCKED) ? true : false,
	'S_VIEWFORUM'			=> true,
	'S_IS_POSTABLE'			=> ($chat_data['forum_type'] == FORUM_POST) ? true : false,
	'U_VIEW_FORUM'		=> append_sid("{$phpbb_root_path}".(defined('IN_PORTAL') ? 'portal' : 'index').".$phpEx", "f=$chat_id"),
	'S_MESSAGE_WINDOW'		=> $message_window ? true : false,
	'S_USER_WINDOW'		=> $user_window ? true : false,
	'S_FORM_WINDOW'		=> $form_window ? true : false,
	'S_BAR_WINDOW'		=> $bar_window ? true : false,
	'S_BBCODE_WINDOW'		=> $bbcode_window ? true : false,
	'S_BBCODE_ENABLED'		=> $config['ppkbb_chat_enable_bbcodes'] ? true : false,
	'S_CHAT_NOTIN'			=> !$chat_user ? true : false,
	'S_ONLINE_WINDOW'		=> $online_window ? true : false,
	'ONLINE_MESSAGE'		=> $online_window && $online_message ? $online_message : '',
	'U_CHAT_LINK'		=> $link,
	'FILENAME'	=> "{$phpbb_root_path}chat/message_user.$phpEx?f=$chat_id&chatkey=$chat_key",
	'TIME'	=> intval(@$max_id['date']),
	'LAST_ID'	=> intval(@$max_id['id']),
	'REFRESH' => $config['ppkbb_chat_murefresh'] * 1000,
	'FORUM_ID'	=> $chat_id,
	'CHATKEY'	=> $chat_key,
	'WAITTIME'	=> $config['ppkbb_chat_waittime'],
	'FULLTIME'	=> $is_canskipdisbutton ? false : 'fulltime();',
	'CHATSMILIES'	=> chat_generate_smilies('inline', $chat_id),
	'PHPEX'		=> $phpEx,
	'HIDDEN_OPT' => $is_canhiddeninchat ? '<input type="checkbox" title="'.$user->lang['CHAT_SETHIDDENHLP'].'" checked="checked" id="hid_button" name="u_hidden" value="1" onclick="set_hidden();" />' : '',
	'GMODE_OPT' => $is_canusegmode ? '<input type="checkbox" title="'.$user->lang['CHAT_GMODEHLP'].'" id="gmode_button" name="u_gmode" value="1" onclick="get_gmode();" />' : '',
	'CHATPM_OPT' => $is_cansendchatpm ? true : false,
	'ACOMMANDS_OPT' => $is_canuseacommands ? true : false,
	'USER_ID' => $user_id,
	'QBAN_TIME' => $config['ppkbb_chat_qbantime'] ? $config['ppkbb_chat_qbantime'] : 1,
	'ERROR' => $chat_error && @$user->lang['CHAT_ERRDESCR'][$chat_error] ? $user->lang['CHAT_ERRDESCR'][$chat_error] : false,
	'ADM_OPT' => $is_canuseacommands && $chat_user ? sprintf($user->lang['CHAT_DELETE'], $user->lang['CHAT_MCLEAN'], $user->lang['CHAT_UCLEAN'], ($is_canviewarchive ? $user->lang['CHAT_ACLEAN'] : '')) : '',
	'ARCH_OPT' => $is_canviewarchive && $chat_user ? sprintf($user->lang['CHAT_VIEW_ARCHIVE'], "{$phpbb_root_path}chat/message_user.$phpEx?f=$chat_id&chatkey=$chat_key&amp;varch=1") : '',
	'CHAT_TUPDATE' => sprintf($user->lang['CHAT_TUPDATE'], $config['ppkbb_chat_murefresh']),
	'CHAT_HSTEP' => $ppkbb_chat_height[0],
	'CHAT_HMIN' => $ppkbb_chat_height[1],
	'CHAT_HMAX' => $ppkbb_chat_height[2],
	'IN_PORTAL' => defined('IN_PORTAL') ? true : false,
	'CHAT_MINIMIZED' => $config['ppkbb_chat_enable']==2 ? true : false,
	)
);

//From includes/functions_posting.php
function chat_generate_smilies($mode, $chat_id)
{
	global $db, $config, $phpbb_root_path;

	$display_link = false;
	$chat_smilies='
	<table width="100%" cellpadding="0" cellspacing="5" border="0">';

	$last_url = '';

	$sql = 'SELECT *
		FROM ' . SMILIES_TABLE .'
		ORDER BY smiley_order';
	$result = $db->sql_query($sql);

	$smilies = array();
	while($row=$db->sql_fetchrow($result))
	{
		if (empty($smilies[$row['smiley_url']]))
		{
			$smilies[$row['smiley_url']] = $row;
		}
	}
	$db->sql_freeresult($result);

	if (sizeof($smilies))
	{
		foreach ($smilies as $row)
		{
			$chat_smilies.='<tr><td align="center"><a href="javascript:void(0);" onClick="javascript:inserttext(\' '.$row['code'].' \');"><img alt="'.$row['emotion'].'" title="'.$row['emotion'].'" width="'.$row['smiley_width'].'" height="'.$row['smiley_height'].'" src="'.$phpbb_root_path . $config['smilies_path'] . '/' . $row['smiley_url'].'" /></a></td></tr>';
		}
	}
	$chat_smilies.='</table>';
	return $chat_smilies;

}

function create_chatkey($user_id)
{
	global $user, $db;

	$str=$user->data['user_chatkey'];
	if(!$str)
	{
		$str=microtime().date('Y-m-d H:i:s').$user->data['username'].$user->data['user_form_salt'];
		$str=md5($str);

		$sql = 'UPDATE ' . USERS_TABLE . "
			SET user_chatkey = '$str'
			WHERE user_id = '" . $user_id ."' LIMIT 1";
		$result=$db->sql_query($sql);
		if(!$result)
		{
			return false;
		}
	}

	return $str;
}

?>
